package com.punai.monthanalysis.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.punai.common.utils.DateUtil;
import com.punai.common.utils.NumberUtil;
import com.punai.common.utils.StringUtil;
import com.punai.externalccb.constants.CCBConstants;
import com.punai.externalccb.domain.*;
import com.punai.externalccb.mapper.*;
import com.punai.monthanalysis.bo.ProjectMonthInfoBo;
import com.punai.monthanalysis.bo.TableAndGraphDataBo;
import com.punai.monthanalysis.service.YdSummaryHzService;
import com.punai.monthanalysis.vo.SummaryVo;
import com.punai.prodatalibrary.domain.LibProjectInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class YdSummaryHzServiceImpl implements YdSummaryHzService{

    @Autowired
    private YdTimeMapper ydTimeMapper;
    @Autowired
    private YdSummaryMapper ydSummaryMapper;
    @Autowired
    private EcoCbhzinfoMapper ecoCbhzinfoMapper;
    @Autowired
    private YdczSummaryMapper ydczSummaryMapper;
    @Autowired
    private YdCbfeeiteminfoStandardMapper ydCbfeeiteminfoStandardMapper;
    @Autowired
    private EcoCbinfoMapper ecoCbinfoMapper;


    @Override
    public TableAndGraphDataBo selectTableAndGraphData(SummaryVo vo) {
        String proId = vo.getProId();
        String start = vo.getStart();
        String end = vo.getEnd();

        List<YdTime> ydTimes = ydTimeMapper.selectList(
                Wrappers.<YdTime>lambdaQuery()
                        .eq(YdTime::getProId, proId)
                        .ge(StrUtil.isNotBlank(vo.getStart()),YdTime::getStartdate, DateUtil.getDate(start + "-01"))
                        .le(StrUtil.isNotBlank(vo.getEnd()),YdTime::getStartdate, DateUtil.getDate(end + "-01"))
                        .eq(YdTime::getStagetype, CCBConstants.CCB_TYPE.YDCBFX.getCode())
                        .orderByAsc(YdTime::getStartdate)
        );

        if (ydTimes.isEmpty()) {
            return new TableAndGraphDataBo();
        }

        List<Integer> timeIds = ydTimes.stream().map(YdTime::getOid).collect(Collectors.toList());

        List<YdSummary> ydSummaryList = ydSummaryMapper.selectList(
                Wrappers.<YdSummary>lambdaQuery()
                        .in(YdSummary::getYdDate, timeIds)
                        .eq(YdSummary::getProId, proId)
                        .eq(YdSummary::getName, "合计")
                        .eq(YdSummary::getStagetype, CCBConstants.CCB_TYPE.YDCBFX.getCode())
        );

        Map<Integer, List<YdSummary>> ydsmmaryMap = ydSummaryList.stream().collect(Collectors.groupingBy(YdSummary::getYdDate));


        List<String> names = new ArrayList<>();
        List<Map<String,Object>> dataTable = new ArrayList<>();
        /*
         项目总产值（万元）
         计划成本（万元）
         实际成本（万元）
         当月计划偏差率（%）
         累计计划偏差率（%）
         */
        Map<String,Object> xmzczMap = new LinkedHashMap<>();
        xmzczMap.put("itemName","项目总产值（万元）");
        Map<String,Object> jhcbMap = new LinkedHashMap<>();
        jhcbMap.put("itemName","计划成本（万元）");
        Map<String,Object> sjcbMap = new LinkedHashMap<>();
        sjcbMap.put("itemName","实际成本（万元）");
        Map<String,Object> dyjhpclMap = new LinkedHashMap<>();
        dyjhpclMap.put("itemName","当月计划偏差率（%）");
        Map<String,Object> ljjhpclMap = new LinkedHashMap<>();
        ljjhpclMap.put("itemName","累计计划偏差率（%）");

        for (YdTime ydTime : ydTimes) {
            Integer oid = ydTime.getOid();
            String monthName = DateUtil.dateToyM(ydTime.getStartdate());
            names.add(monthName);
            List<YdSummary> ydSummarys = ydsmmaryMap.get(ydTime.getOid());
            YdSummary ydSummary = ydSummarys.get(0);
            // 开累产值
            BigDecimal monthCz = NumberUtil.divide(ydSummary.getMonthCz(),BigDecimal.valueOf(10000));
            xmzczMap.put("key" + monthName,monthCz);
            xmzczMap.put("ydTimeId" + monthName,oid);
            // 计划成本
            BigDecimal targetTotal = NumberUtil.divide(ydSummary.getTargetTotal(),BigDecimal.valueOf(10000));
            jhcbMap.put("key" + monthName,targetTotal);
            jhcbMap.put("ydTimeId" + monthName,oid);
            // 实际成本
            BigDecimal monthCb = NumberUtil.divide(ydSummary.getMonthCb(),BigDecimal.valueOf(10000));
            sjcbMap.put("key" + monthName,monthCb);
            sjcbMap.put("ydTimeId" + monthName,oid);
            // 累计计划偏差率 = 开累实际利润率 - 开累计划利润率
            // 开累计划利润率 = 开工累计计划利润  /  开工累计产值金额
            // 当月计划偏差率
            BigDecimal monthLrlpc = NumberUtil.subtract(ydSummary.getMonthRealLrl(), ydSummary.getMonthLrl());
            dyjhpclMap.put("key" + monthName,monthLrlpc);
            dyjhpclMap.put("ydTimeId" + monthName,oid);
            // 累计计划偏差率  = 开累实际利润率 - 开累计划利润率
            BigDecimal costsLrlpc = NumberUtil.subtract(ydSummary.getCostsRealLrl(), ydSummary.getCostsLrl());
            ljjhpclMap.put("key" + monthName,costsLrlpc);
            ljjhpclMap.put("ydTimeId" + monthName,oid);
        }
        dataTable.add(xmzczMap);
        dataTable.add(jhcbMap);
        dataTable.add(sjcbMap);
        dataTable.add(dyjhpclMap);
        dataTable.add(ljjhpclMap);

        TableAndGraphDataBo tableAndGraphDataBo = new TableAndGraphDataBo();
        tableAndGraphDataBo.setNames(names);
        tableAndGraphDataBo.setDataTable(dataTable);
        return tableAndGraphDataBo;
    }

    @Override
    public ProjectMonthInfoBo getCbkhsjfxbInfo(LibProjectInfo libProjectInfo, String monthId) {
        ProjectMonthInfoBo result = new ProjectMonthInfoBo();

        //总建筑面积
        List<EcoCbinfo> ecoCbinfos = ecoCbinfoMapper.selectList(Wrappers.<EcoCbinfo>lambdaQuery()
                .eq(EcoCbinfo::getName, "总建筑面积(m2)")
                .eq(EcoCbinfo::getProId, libProjectInfo.getProId())
                .eq(EcoCbinfo::getBidnodeid, 1)
                .eq(EcoCbinfo::getStagetype, CCBConstants.CCB_TYPE.YDCBFX.getCode()));
        BigDecimal zjzmj = ecoCbinfos.stream().map(EcoCbinfo::getContent).filter(Objects::nonNull).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);

        result.setProName(libProjectInfo.getProjectName());
        result.setProDept(libProjectInfo.getProjectDept());
        result.setJzmj(zjzmj);
//        result.setCbzb(); //承包指标 目前无值
        return result;
    }

    @Override
    public ProjectMonthInfoBo getProjectMonthInfo(String proId, String monthId,String type) {
        ProjectMonthInfoBo result = new ProjectMonthInfoBo();
        List<String> names = new ArrayList<String>() {{
            add("合计");
            add("其他措施费");
        }};
        List<YdSummary> ydSummaryList = ydSummaryMapper.selectList(Wrappers.<YdSummary>lambdaQuery()
                .in(YdSummary::getName,names)
                .eq(YdSummary::getProId, proId)
                .eq(YdSummary::getYdDate, monthId)
                .eq(YdSummary::getStagetype, CCBConstants.CCB_TYPE.YDCBFX.getCode()));
        Map<String, List<YdSummary>> ydSummaryMap = ydSummaryList.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(YdSummary::getName, Collectors.toList()));
        //人工费总量动态控制表
        if (StringUtil.equals(type,"dwgcrgfzldtkzb")){
            List<YdSummary> summaryList = ydSummaryMap.get("合计");
            List<YdCbfeeiteminfoStandard> standardList = ydCbfeeiteminfoStandardMapper.selectList(Wrappers.<YdCbfeeiteminfoStandard>lambdaQuery()
                    .eq(YdCbfeeiteminfoStandard::getProId, proId)
                    .eq(YdCbfeeiteminfoStandard::getYdDate, monthId)
                    .eq(YdCbfeeiteminfoStandard::getStagetype, CCBConstants.CCB_TYPE.YDCBFX.getCode())
                    .eq(YdCbfeeiteminfoStandard::getOpid, "0")
                    .eq(YdCbfeeiteminfoStandard::getFeeType, "1"));

            BigDecimal monthPdCz = summaryList.stream().map(YdSummary::getCostsCz).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal klRgfSjcb = standardList.stream().map(YdCbfeeiteminfoStandard::getActualCostNoTaxTotal).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            result.setMonthPdCz(monthPdCz);
            result.setKlRgfSjcb(klRgfSjcb);
            result.setKlRgfZczbl(NumberUtil.divideNew(klRgfSjcb,2,monthPdCz));
            //预算工日单价(总承包合同单价-工具手填) 无值

            return result;
        }else if (StringUtil.equals(type,"dwgccsffxb")){
            //措施费分析表
            List<YdSummary> summaryHJList = ydSummaryMap.get("合计");
            List<YdSummary> summaryList = ydSummaryMap.get("其他措施费");

            List<EcoCbhzinfo> cbhzinfoList = ecoCbhzinfoMapper.selectList(Wrappers.<EcoCbhzinfo>lambdaQuery()
                    .eq(EcoCbhzinfo::getName, "完成产值总建筑面积(m2)")
                    .eq(EcoCbhzinfo::getProId, proId)
                    .eq(EcoCbhzinfo::getYdDate, monthId)
                    .eq(EcoCbhzinfo::getBidnodeid,1)
                    .eq(EcoCbhzinfo::getStagetype, CCBConstants.CCB_TYPE.YDCBFX.getCode()));

            //总建筑面积
            List<EcoCbinfo> ecoCbinfos = ecoCbinfoMapper.selectList(Wrappers.<EcoCbinfo>lambdaQuery()
                    .eq(EcoCbinfo::getName, "总建筑面积(m2)")
                    .eq(EcoCbinfo::getProId, proId)
                    .eq(EcoCbinfo::getBidnodeid, 1)
                    .eq(EcoCbinfo::getStagetype, CCBConstants.CCB_TYPE.YDCBFX.getCode()));

            BigDecimal ysZcsf = summaryList.stream().filter(v -> v.getPid() == 0 && v.getPid() != null).map(YdSummary::getCostsCz).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal mqCz = summaryHJList.stream().map(YdSummary::getCostsCz).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sjcbCsf = summaryList.stream().map(YdSummary::getMonthCb).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal ywcJzmj = cbhzinfoList.stream().map(EcoCbhzinfo::getContent).filter(Objects::nonNull).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal zjzmj = ecoCbinfos.stream().map(EcoCbinfo::getContent).filter(Objects::nonNull).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);



            result.setYsZcsf(ysZcsf);
            //措施费包死总价 无值
            result.setMqCz(mqCz);
            result.setZjzmj(zjzmj);
            result.setSjcbCsf(sjcbCsf);
            //实际成本占措施费比率 = 实际成本措施费 / 措施费包死总价（工具手填）  没有  包死总价没有,无法计算
            result.setCsfJy(NumberUtil.subtract(ysZcsf,sjcbCsf)); //预算总措施费（完成措施费产值） - 实际成本措施费
            result.setYwcJzmj(ywcJzmj);
            result.setSjcbCsfDj(NumberUtil.divide(sjcbCsf,ywcJzmj));
            return result;
        }
//        // 建筑面积之类的
//        List<EcoCbhzinfo> ecoCbhzinfos = ecoCbhzinfoMapper.selectList(
//                Wrappers.<EcoCbhzinfo>lambdaQuery()
//                        .eq(EcoCbhzinfo::getProId, proId)
//                        .eq(EcoCbhzinfo::getYdDate, monthId)
//        );
//        if (ecoCbhzinfos.isEmpty()) {
//            return result;
//        }
//
//
//        for (EcoCbhzinfo ecoCbhzinfo : ecoCbhzinfos) {
//            // zjz 完成产值总建筑面积(m2)
//            // dsjz 完成产值地上建筑面积(m2)
//            // dxjz 完成产值地下建筑面积(m2)
//            if (ecoCbhzinfo.getCode().equals("zjz")) {
//                result.setCzZmj(Convert.toBigDecimal(ecoCbhzinfo.getContent()));
//            }
//            if (ecoCbhzinfo.getCode().equals("dsjz")) {
//                result.setCzDsmj(Convert.toBigDecimal(ecoCbhzinfo.getContent()));
//            }
//            if (ecoCbhzinfo.getCode().equals("dxjz")) {
//                result.setCzDxmj(Convert.toBigDecimal(ecoCbhzinfo.getContent()));
//            }
//        }
//
//
        return result;
    }
}
